<?php

// +----------------------------------------------------------------------
// | APP设备处理
// +----------------------------------------------------------------------
// | Copyright (c) 2015-2024 http://www.yicmf.com, All rights reserved.
// +----------------------------------------------------------------------
// | Author: 微尘 <yicmf@qq.com>
// +----------------------------------------------------------------------

namespace app\event\app;

use app\common\event\Base;
use app\event\ucenter\User as UserEvent;
use app\model\pay\Pay as PayModel;
use app\model\ucenter\User as UserModel;
use app\model\ucenter\UserOauth;
use app\model\ucenter\UserTask as UserTaskModel;
use app\model\app\ThirdRecharge as ThirdRechargeModel;
use app\model\app\ThirdRechargeOrder as ThirdRechargeOrderModel;
use app\model\wechat\WechatFans;
use think\Exception;
use think\facade\Config;
use think\facade\Db;
use think\facade\Env;
use think\facade\Lang;
use think\facade\Log;
use think\facade\Validate;
use think\helper\Str;
use wechat\mch\Pay as WechatMchPay;
use wechat\mch\PayV3;
use wechat\official_account\Qrcode;
use wechat\official_account\Template as TemplateOfficial;
use yicmf\tools\FlowSn;
use yicmf\tools\HttpService;

class ThirdRecharge extends Base
{


    protected $appid = 68;
    protected $appkey = 'RhI1Wk0u5XzcZoQna3GvCVexmwDFSAKq';
    protected $url = 'http://dyr.qhg333.com/';

    public function fail()
    {
        $orders = ThirdRechargeOrderModel::where('status', 0)->whereNull('order_no')->whereTime('create_time', '<', '-10 minutes')->select();
        foreach ($orders as $order) {
            $order['status'] = -1;
            $order->save();
            $task = UserTaskModel::where('task_type', 26)->where('relation_id', $order['id'])->find();
            if ($task) {
                $task['reason'] = '超时未支付';
                $task['status'] = 3;
                $task->save();
            }
        }
    }


    /**
     * 异步通知
     * * userid  商户ID
     * * order_number 订单号
     * *  out_trade_num 商户订单号
     * * otime 成功/失败时间，10位时间戳
     * * state 充值状态；-1取消， 0充值中， 1充值成功 ，2充值失败，3部分成功（-1,2做失败处理；1做成功处理；3做部分成功处理）
     * * mobile 18866667777   充值手机号
     * * remark 备注信息
     * * charge_amount 值成功面额
     * * voucher 凭证
     * * charge_kami 卡密/流水号
     * * sign 签名字符串，用于验签,以保证回调可靠性。
     */
    public function endPay($param)
    {
        try {
            $sign = $param['sign'];
            unset($param['sign']);
            ksort($param);//排序
            $sign_str = http_build_query($param) . '&apikey=' . $this->appkey;
            $mysign = strtoupper(md5(urldecode($sign_str)));
            if ($mysign != $sign) {
                throw new Exception('sign error');
            }
            Db::startTrans();
            if (strpos($param['out_trade_num'], 'X')) {
                $order = ThirdRechargeOrderModel::where('sn', explode('X', $param['out_trade_num'])[0])->lock(true)->where('status', 'in', [1, 3])->find();
            } else if (strpos($param['out_trade_num'], 'M')) {
                $order = ThirdRechargeOrderModel::where('sn', explode('M', $param['out_trade_num'])[0])->lock(true)->where('status', 'in', [1, 3])->find();
            } else {
                $order = ThirdRechargeOrderModel::where('sn', $param['out_trade_num'])->lock(true)->where('status', 'in', [1, 3])->find();
            }
            if (!$order) {
                throw new Exception('充值不存在');
            }

            $order['status'] = $param['state'] + 3;
            if (strpos($param['out_trade_num'], 'X')) {
                $third = ThirdRechargeModel::where('pro_id', explode('X', $param['out_trade_num'])[1])->find();
                if (!$third) {
                    throw new Exception('信息缺失');
                }
                if (!empty($param['charge_amount']) && $param['charge_amount'] > 0) {
                    $order['part_amount'] = $param['charge_amount'] + $order['part_amount'];
                } else {
                    $order['part_amount'] = $third['guide_price'] + $order['part_amount'];
                }
            } else {
                if ($order['status'] == 4 || $order['status'] == 6) {
                    if (!empty($param['charge_amount']) && $param['charge_amount'] > 0) {
                        $order['part_amount'] = $param['charge_amount'] + $order['part_amount'];
                    } else {
                        $order['part_amount'] = $order['all_amount'];
                    }
                }

            }
            $order['voucher'] = $param['voucher'];
            $order['remark'] = $param['remark'];
            $order['send_time'] = time_format($param['otime']);
            $order['order_no'] = $param['order_number'];
            $order['charge_kami'] = isset($param['charge_kami']) ? $param['charge_kami'] : '';

            $task = UserTaskModel::where('task_type', 26)->where('relation_id', $order['id'])->find();
            if (!$task) {
                throw new Exception('任务不存在');
            }
            $task['step'] = $order['status'] == -1 ? 99 : $order['status'];
            //充值状态；-1取消， 0充值中， 1充值成功 ，2充值失败，3部分成功（-1,2做失败处理；1做成功处理；3做部分成功处理）
            if ($order['status'] == 4 || $order['status'] == 6) {
                $task['status'] = 2;
                $order['num_success'] = $order['num_success'] + 1;
            } elseif ($order['status'] == 3) {
                $task['status'] = 1;
            } else {
                $task['reason'] = $order['remark'];
                $task['status'] = 3;
                $order['num_error'] = $order['num_error'] + 1;
            }
            if ($order['is_pause'] == 0) {
                if ($order['third_recharge_id'] >= 500) {
                    if ($order['part_amount'] < $order['all_amount']) {
                        if ($task['status'] == 2 || $task['status'] == 1) {
                            $order['num_send'] = $order['num_send'] + 1;
                            // 到账金额不足，重提
                            $re = $this->_sendCharge($order);
                            if ($re['content']['errno'] != 0) {
                                $order['msg'] = $re['content']['errmsg'];
                                $order['order_no'] = isset($re['content']['data']['order_number']) ? $re['content']['data']['order_number'] : '';
                                $order['status'] = 5;
                            } else {
                                $order['order_no'] = $re['content']['data']['order_number'];
                                $order['status'] = 3;
                            }
                            Log::write($re['content']);
                            $task['step'] = $order['status'];
                            if ($order['status'] == 5) {
                                $task['status'] = 3;
                            } else {
                                $task['status'] = 1;
                            }
                        }
                    }
                } else {
                    if ($order['is_fee'] == 0 && strpos($task['reason'], '授信') == false && ($order['status'] == 2 || $order['status'] == 5)) {
                        // 没有撤单自动重提一次
                        if ($order['is_fee'] == 0 && $order['num_error'] < 2) {
                            if (($order['third_recharge_id'] >= 46 && $order['third_recharge_id'] <= 48) && (strtotime($order['pay_time']) + 3600 * 25) > time())
//                                      if ((($order['third_recharge_id'] >= 46 && $order['third_recharge_id'] <= 48) && (strtotime($order['pay_time']) + 3600*25) > time())
//                                || (($order['third_recharge_id'] >= 31 && $order['third_recharge_id'] <= 40) && (strtotime($order['pay_time']) + 86400 * 2) > time()))
//
                            {
                                $order['num_send'] = $order['num_send'] + 1;
                                $re = $this->_sendCharge($order);
                                if ($re['content']['errno'] != 0) {
                                    $order['msg'] = $re['content']['errmsg'];
                                    $order['order_no'] = isset($re['content']['data']['order_number']) ? $re['content']['data']['order_number'] : '';
                                    $order['status'] = 5;
                                } else {
                                    $order['order_no'] = $re['content']['data']['order_number'];
                                    $order['status'] = 3;
                                }
                                Log::write($re['content']);
                                $task['step'] = $order['status'];
                                if ($order['status'] == 5) {
                                    $task['status'] = 3;
                                } else {
                                    $task['status'] = 1;
                                }
                            }
                        }
                    }
                    if ($order['status'] == 5 || $order['status'] == 2) {
                        // 退费
//                        if ($order['third_recharge_id'] >= 46 && strtotime($order['pay_time']) + 86400 * 2 > time()) {
//                            // 未到时间
//                            $order['status'] = 7;
//                            $amount = $order['amount'] - round($order['amount'] * 0.006, 2) - $order['refund_money'];
//                        } elseif ($order['third_recharge_id'] >= 31 && $order['third_recharge_id'] <= 40 && strtotime($order['pay_time']) + 86400 * 3 > time()) {
//                            // 未到时间
//                            $order['status'] = 7;
//                            $amount = $order['amount'] - round($order['amount'] * 0.006, 2) - $order['refund_money'];
//                        } else {
                        $amount = $order['amount'];
//                        }
//             // 退费
//                    if ($order['is_fee'] == 1 && $order['third_recharge_id'] >= 46 && strtotime($order['pay_time']) + 86400 * 2 > time()) {
//                        // 未到时间
//                        $order['status'] = 7;
//                        $amount = $order['amount'] - round($order['amount'] * 0.006, 2) - $order['refund_money'];
//                    } elseif ($order['is_fee'] == 1 && $order['third_recharge_id'] >= 31 && $order['third_recharge_id'] <= 40 && strtotime($order['pay_time']) + 86400 * 3 > time()) {
//                        // 未到时间
//                        $order['status'] = 7;
//                        $amount = $order['amount'] - round($order['amount'] * 0.006, 2) - $order['refund_money'];
//                    } else {
//                        $order['status'] = 8;
//                        $amount = $order['amount'];
//                    }

                        $order['refund_money'] = $amount;
                        $pay = PayModel::where('relation_id', $order['id'])->where('type', 'life')->find();
                        if ($pay) {
                            if ($pay['payment_code'] == 'alipay') {
                                if ($pay['operation_type'] == 'FREEZE') {
                                    // 预授权
                                    Log::write(11221);
                                    alipay_app_unfreeze_pay($pay, $amount, '订单取消自动退费');
                                    $pay['status'] = -1;
                                    $pay->save();
                                } else {
                                    alipay_app_refund($pay['pay_sn'], $amount, '订单取消自动退费', '系统' . $pay['out_request_no']);
                                    Log::write(1122);
                                }
                                $order['status'] = 8;
                            } elseif ($pay['payment_code'] == 'wxpay' && $amount < 501) {
                                // 微信退款
                                $re = wechat_app_pay_refund($pay, $amount, '订单取消自动退费');
                                Log::write($re);
                                if (isset($re['result_code']) && $re['result_code'] == 'SUCCESS') {
                                    // 成功
                                    $order['status'] = 8;
                                    $pay['gmt_close'] = time_format();
                                    $pay['receipt_amount'] = $amount;
                                    $pay['status'] = -1;
                                    $pay->save();
                                }
                            }
                        }
                    }
                }
            }

            if (!$order->save()) {
                throw new Exception('数据异常');
            }
            $task->save();
            if ($task['status'] == 2) {
                $pay = PayModel::where('relation_id', $order['id'])->where('type', 'life')
                    ->where('payment_code', 'alipay')
                    ->where('operation_type', 'FREEZE')
                    ->find();
                if ($pay) {
                    // 订单完成
                    $pay['action_no'] = $pay['action_no'] + 1;
                    alipay_app_freeze_pay($pay, $pay['total_amount'], $pay['title']);
                    $pay->save();
                }
                $user = UserModel::where('id', $task['user_id'])->find();
                if ($user && $task['commission'] > 0) {
                    if ($order['allow_push'] == 1) {

                        $fan = WechatFans::where('user_id', $order['user_id'])->find();
                        if ($fan) {
                            $oa_data = [
                                'amount3' => ['value' => $order['all_amount'], 'color' => '#000000'],
                                'number2' => ['value' => $order['template'], 'color' => '#000000'],
                                'time12' => ['value' => $order['pay_time'], 'color' => '#000000'],
                                'character_string18' => ['value' => $order['sn'], 'color' => '#000000'],
                                'thing9' => ['value' => $order['name'], 'color' => '#000000'],
                            ];
                            $account['token'] = 'yunfuye1';
                            $account['encoding_aes_key'] = 'BkrUUPz9IgfERTRXmwiIf0RSir4ONBku64EufsZ9EE2';
                            $account['app_secret'] = 'cbdd44c7d119c8b4dd51b74c3030aa75';
                            $account['app_id'] = 'wxd4cc6bfc61b75cc5';
                            $oa = new TemplateOfficial();
                            $oa->initAccount($account);
                            $re = $oa->send($fan['openid'], 'Uy15FE972AzNOhuUbMQkiUwHa0EzGzSi-L7CzZ9sAF0', $oa_data, '');
                        }
                    }
                    UserEvent::exhibitionIncome($user, $task['commission'], $task['title'], 51, $user['id'], $task['task_no'], 0, $order['third_recharge_id'], 14);
                }
            } elseif ($task['status'] == 3) {
                if ($order['allow_push'] == 1) {
                    $fan = WechatFans::where('user_id', $order['user_id'])->find();
                    if ($fan) {
                        $oa_data = [
                            'number2' => ['value' => $order['template'], 'color' => '#000000'],
                            'amount3' => ['value' => $order['all_amount'], 'color' => '#000000'],
                            'thing5' => ['value' => $order['remark'] ?: '失败', 'color' => '#000000'],
                            'thing7' => ['value' => $order['name'], 'color' => '#000000'],
                            'time11' => ['value' => $order['pay_time'], 'color' => '#000000'],
                        ];
                        $account['token'] = 'yunfuye1';
                        $account['encoding_aes_key'] = 'BkrUUPz9IgfERTRXmwiIf0RSir4ONBku64EufsZ9EE2';
                        $account['app_secret'] = 'cbdd44c7d119c8b4dd51b74c3030aa75';
                        $account['app_id'] = 'wxd4cc6bfc61b75cc5';
                        $oa = new TemplateOfficial();
                        $oa->initAccount($account);
                        $re = $oa->send($fan['openid'], 'BFwl_nRGEbsr86f1Gc833kuf06GCQVkIMqUem3vsO9M', $oa_data, '');
                    }
                }


            }
            Db::commit();
            $rep = ['code' => 0, 'message' => '接收成功'];
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            $rep = ['code' => 1, 'message' => $e->getMessage()];
        }
        return $rep;
    }

    /**
     * 退款
     */
    public function back($param, $admin)
    {
        try {

            $order = ThirdRechargeOrderModel::where('id', $param['id'])->where('status', 'in', [1, 2, 5, 6])->find();
            if (!$order) {
                throw new Exception('订单状态不支持退款');
            }
//            ->keyRadio('type', '退款形式', ['全额退', '扣除手续费', '指定金额'])
//                ->keyDecimal('amount', '退款金额', '实际退回金额')
            if ($param['type'] == 0) {
                // 全额退款
                $amount = $order['amount'] - $order['refund_money'];
                $order['status'] = 8;
            } elseif ($param['type'] == 1) {
                $amount = $order['amount'] - round($order['amount'] * 0.006, 2) - $order['refund_money'];
                $order['status'] = 7;
            } else {
                $amount = $param['amount'];
                $order['status'] = 7;
            }
            $order['refund_money'] = $amount + $order['refund_money'];
            if ($order['refund_money'] == $order['amount']) {
                $order['status'] = 8;
            }
            if ($amount <= 0) {
                throw new Exception('订单金额不合法');
            }
//            $pay = PayModel::where('relation_id', $order['id'])->whereNotNull('auth_no')->where('type', 'life')->find();
            $pay = PayModel::where('relation_id', $order['id'])->where('status', 1)->where('type', 'life')->find();
//            $pay = PayModel::where('relation_id', $order['id'])->whereNotNull('api_pay_no')->where('type', 'life')->find();
            if (!$pay) {
                throw new Exception('接口异常');
            }

            $task = UserTaskModel::where('task_type', 26)->where('relation_id', $order['id'])->find();
            if (!$task) {
                throw new Exception('任务不存在');
            }
            $pay['action_no'] = $pay['action_no'] + 1;
            if ($pay['payment_code'] == 'alipay') {

                if ($pay['operation_type'] == 'FREEZE') {
                    // 预授权
                    Log::write(11221);
                    alipay_app_unfreeze_pay($pay, $amount, '订单取消自动退费');
                    $pay['status'] = -1;
                    $pay->save();
                } else {
                    $re = alipay_app_refund($pay['pay_sn'], $amount, '订单取消自动退费', '系统' . $pay['out_request_no']);

                    Log::write(1122);
                    if ($re['code'] != '10000') {
                        throw new Exception($re['msg']);
                    }
                }
            } elseif ($pay['payment_code'] == 'wxpay') {
                // 微信退款
                $re = wechat_app_pay_refund($pay, $amount, '订单取消自动退费');
                if (isset($re['result_code']) && $re['result_code'] == 'SUCCESS') {
                    // 成功
                    $pay['gmt_close'] = time_format();
                    $pay['receipt_amount'] = $amount;
                    $pay['status'] = -1;
                    $pay->save();
                } else {
                    throw new Exception($re['return_msg']);
                }
            } else {
                throw new Exception('当前支付方式不支持退款');
            }
            $order->save();
            $task['status'] = 3;
            $task->save();
            $rep = ['code' => 0, 'message' => '已经提交退费'];
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            $rep = ['code' => 1, 'message' => $e->getMessage()];
        }
        return $rep;
    }

    /**
     * 撤单
     */
    public function cancel($param, $user)
    {
        try {

            $order = ThirdRechargeOrderModel::where('id', $param['id'])->whereNotNull('order_no')->where('status', 3)->find();
            if (!$order) {
                throw new Exception('订单状态不支持撤销');
            }
            $order['is_fee'] = 1;
            $order->save();
            $param = [];
            $param['userid'] = $this->appid;
            $param['out_trade_nums'] = $order['order_no'];
            ksort($param);
            $sign_str = http_build_query($param) . '&apikey=' . $this->appkey;
            $sign = strtoupper(md5(urldecode($sign_str)));
            $param['sign'] = $sign;

            $re = HttpService::post($this->url . 'yrapi.php/index/cancel', $param);
            //yrapi.php/index/cancel
//            dump($this->url . 'yrapi.php/index/cancel');
//            dump($param);
//            exit();
//            dump($re);
            if ($re['content']['errno'] != 0) {
                throw new Exception($re['content']['errmsg']);
            }
            $rep = ['code' => 0, 'message' => '撤单已经申请，请等待状态取消后再退款'];
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            $rep = ['code' => 1, 'message' => $e->getMessage()];
        }
        return $rep;
    }

    /**
     * 撤单
     */
    public function pushScan($id, $fans)
    {
        try {

            $order = ThirdRechargeOrderModel::where('id', $id)->find();
            if (!$order) {
                throw new Exception('订单状态不支持撤销');
            }

            if ($fans['user_id'] && $fans['user_id'] != $order['user_id']) {
                throw new Exception('抱歉，订阅失败，目前同一个微信号仅支持订阅一个合伙人账号通知消息。');
            } elseif (!$fans['user_id']) {
                $oauth = UserOauth::where('union_id', $fans['unionid'])->where('channel', 'weixin')->find();
                if ($oauth && $oauth['user_id'] && $oauth['user_id'] != $order['user_id']) {
                    throw new Exception('抱歉，订阅失败，当前微信已经登录其他合伙人账号。');
                }
                $fans['user_id'] = $order['user_id'];
                $fans->save();
            }
//            $user_oauth = UserOauth::where('open_id', $fans[''])->find();
//            if ($user_oauth && $user_oauth['user_id'] && $user_oauth['user_id'] != $order['user_id']) {
//                throw new Exception('抱歉，订阅失败，目前同一个微信号仅支持订阅一个合伙人账号通知消息。');
//            } elseif ($user_oauth && !$user_oauth['user_id']) {
//                $user_oauth['user_id'] = $order['user_id'];
//                $user_oauth->save();
//            } else {
//                //新增
//                UserOauth::create(['user_id' => $order['user_id'], 'open_id' => $openid,'channel'=>'weixin']);
//            }
            $user = UserModel::where('id', $order['user_id'])->find();
            if ($user) {
                if (empty($user['push_arr'])) {
                    $user['push_arr'] = ['life' => ['wechat']];
                } else {
                    $temp = $user['push_arr'];
                    $temp['life'] = ['wechat'];
                    $user['push_arr'] = $temp;
                }
                $user->save();
            }
            $rep = ['code' => 0, 'message' => '您订阅缴费通知成功'];
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            $rep = ['code' => 1, 'message' => $e->getMessage()];
        }
        return $rep;
    }

    /**
     * 撤单
     */
    public function pause($param, $user)
    {
        try {

            $order = ThirdRechargeOrderModel::where('id', $param['id'])->whereNotNull('order_no')->where('status', 3)->find();
            if (!$order) {
                throw new Exception('订单状态不支持撤销');
            }
            $order['is_pause'] = 1;
            $order->save();
            $param = [];
            $param['userid'] = $this->appid;
            $param['out_trade_nums'] = $order['order_no'];
            ksort($param);
            $sign_str = http_build_query($param) . '&apikey=' . $this->appkey;
            $sign = strtoupper(md5(urldecode($sign_str)));
            $param['sign'] = $sign;

            $re = HttpService::post($this->url . 'yrapi.php/index/cancel', $param);
            //yrapi.php/index/cancel
//            dump($this->url . 'yrapi.php/index/cancel');
//            dump($param);
//            exit();
//            dump($re);
            if ($re['content']['errno'] != 0) {
                throw new Exception($re['content']['errmsg']);
            }
            $rep = ['code' => 0, 'message' => '撤停已经申请，请等待状态取消后再退款'];
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            $rep = ['code' => 1, 'message' => $e->getMessage()];
        }
        return $rep;
    }

    /**
     * 确认完成
     */
    public function confirm($param, $user)
    {
        try {

            $order = ThirdRechargeOrderModel::where('id', $param['id'])->where('status', 'in', [3, 6])->find();
            if (!$order) {
                throw new Exception('订单状态不支持确认');
            }
            $task = UserTaskModel::where('task_type', 26)->where('relation_id', $order['id'])->find();
            if (!$task) {
                throw new Exception('任务不存在');
            }
            $task['status'] = 2;
            if ($task->save()) {
                $user = UserModel::where('id', $task['user_id'])->find();
                if ($user && $task['commission'] > 0) {
                    UserEvent::exhibitionIncome($user, $task['commission'], $task['title'], 51, $user['id'], $task['task_no'], 0, $order['third_recharge_id'], 14);
                }
            } else {
                throw new Exception('保存异常');
            }
            $order['status'] = 4;
            $order['remark'] = '客服手动确认';
            $order->save();

            $rep = ['code' => 0, 'message' => '任务已经完成'];
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            $rep = ['code' => 1, 'message' => $e->getMessage()];
        }
        return $rep;
    }

    /**
     * 重启
     */
    public function restart($param, $user)
    {
        try {
            $order = ThirdRechargeOrderModel::where('id', $param['id'])->where('status', 'in', [1, 2, 5])->find();
            if (!$order) {
                throw new Exception('订单不存在，或者状态不支持');
            }
            $order['num_send'] = $order['num_send'] + 1;
            $order['template'] = $param['template'];
            $order['area'] = $param['area'];
            $order['city'] = $param['city'];

            $re = $this->_sendCharge($order);
            $msg = '重提成功';
            if ($re['content']['errno'] != 0) {
                $order['msg'] = $re['content']['errmsg'];
                $msg = $re['content']['errmsg'];
                $order['order_no'] = isset($re['content']['data']['order_number']) ? $re['content']['data']['order_number'] : '';
                $order['status'] = 5;
                $order->save();
            } else {
                $order['order_no'] = $re['content']['data']['order_number'];
                $order['status'] = 3;
                $order->save();
            }
            Log::write($re['content']);
            $task = UserTaskModel::where('task_type', 26)->where('relation_id', $order['id'])->find();
            if ($task) {
                $task['step'] = $order['status'];
                if ($order['status'] == 5) {
                    $task['status'] = 3;
                } else {
                    $task['status'] = 1;
                }
                $task->save();
            }

            $rep = ['code' => 0, 'message' => $msg];
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            $rep = ['code' => 1, 'message' => $e->getMessage()];
        }
        return $rep;
    }

    protected function _sendCharge($order)
    {
        $param['userid'] = $this->appid;
        $param['out_trade_num'] = $order['sn'];
        $param['product_id'] = $order['third_recharge_id'];
        if ($order['third_recharge_id'] >= 500) {
            if ($order['channel'] == 'elec') {
                $third = ThirdRechargeModel::where('name_type', '国家电网电费')
                    ->where('guide_price', '<=', $order['all_amount'] - $order['part_amount'])
                    ->where('pro_id', '<', 500)
//                    ->where('pro_id', '<', 38)
                    ->order('guide_price DESC')
                    ->find();
                if (!$third) {
                    throw new Exception('异常');
                }
                $param['product_id'] = $third['pro_id'];
            }
            $param['out_trade_num'] = $order['sn'] . 'X' . $param['product_id'] . 'X' . $order['num_send'];
        } else {
            $param['out_trade_num'] = $order['sn'] . 'M' . $order['num_send'];
        }
        $param['mobile'] = $order['template'];
        $param['price'] = $order['amount'];
        if ($order['channel'] == 'elec') {
            $param['area'] = $order['area'];
            $param['city'] = $order['city'];
        }
        $param['notify_url'] = (string)url('/api/notify/third/call', [], false, true);
        ksort($param);
        $sign_str = http_build_query($param) . '&apikey=' . $this->appkey;
        $sign = strtoupper(md5(urldecode($sign_str)));
        $param['sign'] = $sign;
        return HttpService::post($this->url . 'yrapi.php/index/recharge', $param);
    }

    /**
     * 支付回调
     * @param array $param
     * @return array
     */
    public function pay($pay)
    {
        try {
            $order = ThirdRechargeOrderModel::where('id', $pay['relation_id'])->lock(true)->find();
            if (!$order) {
                throw new Exception('订单不存在');
            }
            $order['num_send'] = 1;
            $order['status'] = 1;
            $order['pay_time'] = time_format();
//            if ($order['user_id'] != 16006) {
            $re = $this->_sendCharge($order);
            if ($re['content']['errno'] != 0) {
                $order['msg'] = $re['content']['errmsg'];
//                $order['order_no'] = $re['content']['data']['order_number'];
                $order['status'] = 5;
            } else {
                $order['status'] = 3;
                $order['order_no'] = $re['content']['data']['order_number'];
            }
//            } else {
//                $order['status'] = 5;
//                $order['msg'] = 'tiaos';
//            }
            if (!$order->save()) {
                throw new Exception('数据ques');
            }
            Log::write($re['content']);

            $task = UserTaskModel::where('task_type', 26)->where('relation_id', $order['id'])->find();
            if ($task) {
                $task['step'] = $order['status'];
                if ($order['status'] == 5) {
                    $task['status'] = 3;
                } else {
                    $task['status'] = 1;
                }
                $task->save();
            }
            $balance = $this->getBalance();
            if ($balance < 1500) {
                $oa_data = [
                    'thing3' => ['value' => '九九生活-缴费', 'color' => '#000000'],
                    'phone_number18' => ['value' => '13011113333', 'color' => '#000000'],
                    'character_string2' => ['value' => 'cz', 'color' => '#000000'],
                    'amount6' => ['value' => $balance, 'color' => '#000000'],
                    //                'keyword1'=> ['value'=>$auth['idcard_name'], 'color'=>'#000000'],
                    //                'keyword2'=> ['value'=>time_format(), 'color'=>'#000000'],
                    'time13' => ['value' => time_format(), 'color' => '#000000'],
                ];
                $account['token'] = 'yunfuye1';
                $account['encoding_aes_key'] = 'BkrUUPz9IgfERTRXmwiIf0RSir4ONBku64EufsZ9EE2';
                $account['app_secret'] = 'cbdd44c7d119c8b4dd51b74c3030aa75';
                $account['app_id'] = 'wxd4cc6bfc61b75cc5';
                $oa = new TemplateOfficial();
                $oa->initAccount($account);
                $re = $oa->send('oAAIg61Gq__Y_hEJqzOc5iJIbkWk', 'WsQr3fXxkekM039dy0rYtP_G2Zoqf5j_y66Rvw7RujA', $oa_data, '');
            }
            $data['code'] = 0;
            $data['data'] = 1;
            $data['message'] = '操作成功';
        } catch (Exception $e) {
            $data['code'] = 1;
            $data['f'] = $e->getFile();
            $data['l'] = $e->getLine();
            $data['message'] = $e->getMessage();
        }
        return $data;
    }

    /**
     * 下单充值
     * @param array $param
     * @param UserModel $user
     * @return array
     */
    public function order($param, $user)
    {
        try {
            if (!$user) {
                throw new Exception('请先登录');
            }

            $recharge = ThirdRechargeModel::where('id', $param['recharge_id'])->find();
//            $recharge = ExchangeCouponModel::where('branch_id', 10000221)->find();
//            $recharge = ExchangeCouponModel::where('id', 495)->find();
            if (!$recharge) {
                throw new Exception('信息异常');
            }
            if ($recharge['id'] < 30) {
                //throw new Exception('抱歉，月底充值记录过多，暂时不新增充值请求');
            }
            if ($recharge['status'] != 1) {
                throw new Exception('库存不足');
            }
            if ($recharge['is_sale'] != 1) {
                throw new Exception('接口已经下架');
            }
            $re = ThirdRechargeOrderModel::where('template', $param['template'])->where('status', 'in', [1, 3])->find();
            if ($re) {
                throw new Exception('同一个账号同时只能提交一次充值');
            }

            $order['sn'] = FlowSn::build('9');
            if ($param['channel'] == 'mobile') {
                $re = Validate::checkRule($param['template'], 'mobile');

                if (!$re) {
                    throw new Exception('手机号不合法');
                }

                if (strpos($param['template'], '165') === 0) {
                    throw new Exception('抱歉，165号段暂不支持');
                }
                if (strpos($param['template'], '170') === 0) {
                    throw new Exception('抱歉，170号段暂不支持');
                }
                if (strpos($param['template'], '162') === 0) {
                    throw new Exception('抱歉，162号段暂不支持');
                }
                if (strpos($param['template'], '167') === 0) {
                    throw new Exception('抱歉，167号段暂不支持');
                }
                if (strpos($param['template'], '171') === 0) {
                    throw new Exception('抱歉，171号段暂不支持');
                }
                //https://api.asilu.cc/phone/?phone=18299544693
            } elseif ($param['channel'] == 'elec') {
                if (empty($param['template'])) {
                    throw new Exception('请填写户号');
                }
                if (strlen($param['template']) > 13 || strlen($param['template']) < 10) {
                    throw new Exception('请核实户号是否正确');
                }
                if (empty($param['area'])) {
                    throw new Exception('请选择地区');
                }
            }
            $order['channel'] = $param['channel'];
            $order['allow_push'] = isset($param['allow_push']) ? $param['allow_push'] : 0;
            $order['area'] = isset($param['area']) ? $param['area'] : '';
            $order['city'] = isset($param['city']) ? $param['city'] : '';
            $order['channel_name'] = $param['channel_name'];
            $order['user_id'] = $user['id'];
            $order['all_amount'] = $recharge['guide_price'];
            $order['third_recharge_id'] = $recharge['pro_id'];
            $order['status'] = 0;
            $order['amount'] = $recharge['sale_price'];
            $order['name'] = $recharge['name'];
            $order['template'] = $param['template'];
            $order['commission'] = $recharge['back_price'];
            $order = ThirdRechargeOrderModel::create($order);
            if (!$order) {
                throw new Exception('订单创建失败');
            }
            $userTask['task_id'] = 14;
            $userTask['relation_id'] = $order['id'];
            $userTask['task_type'] = 26;
            $userTask['user_id'] = $user['id'];
            $userTask['agent_id'] = $user['agent_id'];
            $userTask['title'] = $recharge['name'];
            $userTask['money'] = $order['amount'];
            $userTask['commission'] = $recharge['back_price'];
            $userTask['task_no'] = $order['sn'];
//            $userTask['end_time'] = time() + 30 * 86400;
            $userTask['step'] = 0;
            $userTask['submit_info'] = $order->toArray();
            $userTask['status'] = 0;
            $task = UserTaskModel::create($userTask);
            if (!$task) {
                throw new Exception('系统故障');
            }

            $insert = [];
            $insert['type'] = 'life';
            $insert['user_id'] = $user['id'];
            $insert['agent_id'] = $user['agent_id'];
//            $insert['payment_code'] = $this->param['payment_code'];
            $insert['payment_code'] = isset($param['payment_code']) ? $param['payment_code'] : 'alipay';
            $insert['api_pay_status'] = '';
            $insert['pay_sn'] = $order['sn'];
            $insert['relation_id'] = $order['id'];
            $insert['total_amount'] = $order['amount'];
            $insert['title'] = '生活缴费';
            $pay = PayModel::create($insert);
            if (!$pay) {
                throw new Exception('订单信息创建异常');
            }
            $data['data']['wechat'] = '';
            if ($order['allow_push']) {
                // 查询用户是否关注
                $fans = WechatFans::where('user_id', $order['user_id'])->find();
                if (!$fans) {
                    // 需要引导关注
                    $account['token'] = 'yunfuye1';
                    $account['encoding_aes_key'] = 'BkrUUPz9IgfERTRXmwiIf0RSir4ONBku64EufsZ9EE2';
                    $account['app_secret'] = 'cbdd44c7d119c8b4dd51b74c3030aa75';
                    $account['app_id'] = 'wxd4cc6bfc61b75cc5';
                    $qr = new Qrcode();
                    $qr->initAccount($account);
                    $qrs = $qr->qrcodeCreate('life_' . $order['id'], 3600);
                    if (count($qrs) == 3) {

                        $qr = '/upload/wechat/life/' . time_format(time(), 'y/md') . '/' . $order['id'] . '_' . $user['shareCode'] . '.png';
                        $dir = public_path() . 'upload/wechat/life/' . time_format(time(), 'y/md') . '/';
                        if (!is_dir($dir)) {
                            //第三个参数是“true”表示能创建多级目录，iconv防止中文目录乱码
                            mkdir(iconv("UTF-8", "GBK", $dir), 0777, true);
                        }

                        if (is_file(public_path() . $qr)) {
                            $file_p = public_path() . $qr;
                            @unlink($file_p);
                        }
                        $errorCorrectionLevel = 'L';//容错级别
                        include_once app()->getRootPath() . 'extend/phpqrcode.php';
                        \QRcode::png($qrs['url'], public_path() . $qr, $errorCorrectionLevel, 20, 2);

                        $data['data']['wechat'] = request()->domain() . $qr;
                    }
                }
            }

            // 微信二维码
            if (isset($param['is_h5']) && 1 == $param['is_h5']) {
                $pay['payment_code'] = 'alipay';
                $pay->save();
//                if ($user['id'] == 16006) {
//                    $data['data']['pay'] = ['payment' => 'alipay', 'order_info' => alipay_app_h5_pre_pay($pay['pay_sn'], 0.1, $pay['title'], $pay['type'])];;
//                }else{
//                $url = 'https://v3.yunfuye.com/2.html?pay_id='.$pay['id'];
//                $data['data']['pay'] = ['webview' => 0,
//                    'payment' => $insert['payment_code'],
//                    'alipay_url' => 'https://web.yunfuye.com/#/pages/other/alipay?pay_id=' . $pay['id'],
//                    'pay' => $pay,
//                    'order_info' => alipay_h5_pay($pay['pay_sn'], $pay['total_amount'], $pay['title'], $pay['type'])
//                ];
                // iOS预授权
                $data['data']['pay'] = ['webview' => 0,
                    'payment' => $insert['payment_code'],
                    'alipay_url' => 'https://web.yunfuye.com/#/pages/other/alipay?pay_id=' . $pay['id'],
                    'pay' => $pay,
                    'order_info' => alipay_h5_pay($pay['pay_sn'], $pay['total_amount'], $pay['title'], $pay['type'])
                ];
            } else {
                // APP支付
                if ($insert['payment_code'] == 'wxpay') {
                    if ($user['id'] == 160016) {
                        //生成微信支付预订单信息
                        $wechat_config = [
                            'appid' => 'wx7c83e79f78fdfa10',
                            'mch_id' => '1697093647',
                            'api_key' => 'qC04wNxXUFVv2eEItzWpdb8BSPMTkHln',
                            'appsecret' => '',
                            'notify_url' => (string)url('/api/notify/pay/wechat', [], false, true),
                        ];

                        $order_no = date('YmdHis') . rand(1000, 9999);
                        $money = 1;
                        $wechat = new PayV3($wechat_config);
                        $wechat_data = $wechat->wx_pay($pay['title'], $money, $order_no, 'aid_order');

                        if ($wechat_data['code'] != 200) {
                            echo $wechat_data['msg'];
                            die;
                        }
                        $result = ['order_no' => $order_no, 'money' => $money, 'wechat_data' => $wechat_data,];

                        $data['data']['pay'] = ['webview' => 0, 'payment' => 'wxpay', 'order_info' => $wechat_data];
                    } else {

                        $data['data']['pay'] = ['webview' => 0, 'payment' => 'wxpay', 'order_info' => wechat_app_pay($pay)];;
                    }


                } else {
                    //            $webview = (string)url('/api/notify/alipay/h5',['pay_sn'=>$pay['pay_sn']],true,true);
//            $this->param['pay'] = ['webview'=>1,'url'=>$webview,'payment' => $insert['payment_code'], 'order_info' => alipay_app_pay($pay['pay_sn'], $pay['total_amount'], $pay['title'], $pay['type'])];
                    //   $this->param['pay'] = ['webview' => 0, 'payment' => $insert['payment_code'], 'order_info' => alipay_app_pay($pay['pay_sn'], $pay['total_amount'], $pay['title'], $pay['type'])];
                    $data['data']['pay'] = ['payment' => 'alipay', 'order_info' => alipay_app_pre_pay($pay['pay_sn'], $pay['total_amount'], $pay['title'], $pay['type'])];;

                }
//                }

            }

            $data['code'] = 0;
            $data['message'] = '操作成功';
        } catch (Exception $e) {
            $data['code'] = 1;
            $data['f'] = $e->getFile();
            $data['l'] = $e->getLine();
            $data['message'] = $e->getMessage();
        }
        return $data;
    }

    public function info()
    {
//        $param = ["参数名称"=>"参数值",...];
        $param['userid'] = $this->appid;
        ksort($param);
        $sign_str = http_build_query($param) . '&apikey=' . $this->appkey;
        $sign = strtoupper(md5(urldecode($sign_str)));
        $param['sign'] = $sign;
        $httpdata = $param;
//        $re = HttpService::post($this->url.'yrapi.php/index/typecate',$param);
//        $re = HttpService::post($this->url . 'yrapi.php/index/elecity', $param);
//        $re = HttpService::post($this->url . 'yrapi.php/index/product', $param);
        $re = HttpService::post($this->url . 'yrapi.php/index/user', $param);
        dump($re['content']['data']);
    }

    protected function getBalance()
    {
        $param['userid'] = $this->appid;
        ksort($param);
        $sign_str = http_build_query($param) . '&apikey=' . $this->appkey;
        $sign = strtoupper(md5(urldecode($sign_str)));
        $param['sign'] = $sign;
        $re = HttpService::post($this->url . 'yrapi.php/index/user', $param);
        return $re['content']['data']['balance'];
    }

    public function city()
    {
        if (cache('third_city')) {
            $data = json_decode(cache('third_city'), true);
        } else {
            $param['userid'] = $this->appid;
            ksort($param);
            $sign_str = http_build_query($param) . '&apikey=' . $this->appkey;
            $sign = strtoupper(md5(urldecode($sign_str)));
            $param['sign'] = $sign;
            $re = HttpService::post($this->url . 'yrapi.php/index/elecity', $param);
            cache('third_city', json_encode($re['content']['data']), 3600);
            $data = $re['content']['data'];
        }
        return $data;
    }

    /**
     * 异步通知
     * userid  商户ID
     * order_number 订单号
     *  out_trade_num 商户订单号
     * otime 成功/失败时间，10位时间戳
     * state 充值状态；-1取消， 0充值中， 1充值成功 ，2充值失败，3部分成功（-1,2做失败处理；1做成功处理；3做部分成功处理）
     * mobile 18866667777   充值手机号
     * remark 备注信息
     * charge_amount 值成功面额
     * voucher 凭证
     * charge_kami 卡密/流水号
     * sign 签名字符串，用于验签,以保证回调可靠性。
     * @param $param
     * @return array
     */
    public function notify($param)
    {
        try {
            $sign = $param['sign'];
            unset($param['sign']);
            ksort($param);//排序
            $sign_str = http_build_query($param) . '&apikey=' . $this->appkey;
            $mysign = strtoupper(md5(urldecode($sign_str)));
            if ($mysign != $sign) {
                throw new Exception('sign error');
            }


            $data['code'] = 0;
            $data['time'] = time_format();
            $data['message'] = '操作成功';
        } catch (Exception $e) {
            $data['code'] = 1;
            $data['f'] = $e->getFile();
            $data['l'] = $e->getLine();
            $data['message'] = $e->getMessage();
        }
        return $data;
    }


}
